/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import QtQuick 2.12
import org.ukui.tablet 1.0
import QtGraphicalEffects 1.0
import "createUninstallDialog.js" as UninstallJs
import "launcherController.js" as Controller
import "groupController.js" as GroupPageController
import org.ukui.qqc2style.private 1.0 as StylePrivate
import "./baseComponent"

LauncherGridViewDelegateItem {
    id: itemRoot
    width: modelData.columnSpan * Style.appIconGridWidth
    height: modelData.rowSpan * Style.appIconGridHeight
    rowSpan: modelData.rowSpan
    columnSpan: modelData.columnSpan

    property int itemId: modelData.id
    property int groupId: root.groupId
    property int type: modelData.type
    property alias launcherViewAppIcon: appIcon

    Drag.active: dragMousearea.drag.active && dragEnable
    Drag.hotSpot.x: Style.appIconGridWidth / 2
    Drag.hotSpot.y: Style.appIconGridHeight / 2

    states: [
        State {
            when: itemRoot.Drag.active
            ParentChange {
                target: itemRoot
                parent: topLayer
            }

            AnchorChanges {
                target: itemRoot
                anchors.horizontalCenter: undefined
                anchors.top: undefined
            }
            PropertyChanges {
                target: appIcon
                width: appIcon.width * 1.1
                height: appIcon.height * 1.1
                containerState: LauncherItem.Dragging
            }
        }
    ]

    MouseArea {
        id: dragMousearea
        anchors.centerIn: parent
        width: modelData.columnSpan * Style.appIconGridWidth - Style.tabletScaleFactor * 40
        height: modelData.rowSpan * Style.appIconGridHeight - Style.tabletScaleFactor * 40
        hoverEnabled: true
        Drag.active: false
        drag.target: undefined
        pressAndHoldInterval: modelData.state === LauncherItem.Editable ?
                                  100 : Style.pressIntervalToEditable
        property bool isScrolling: false
        property var mapContainer: GroupController.groupContainer
        property bool isChangeContainerPage: false

        Timer {
            id: scrollingTimer
            interval: 600
            onTriggered: dragMousearea.isScrolling = false
        }
        Timer {
            id: changeContainerPageTimer
            interval: 600
            onTriggered: {
                dragMousearea.isChangeContainerPage = true
            }
        }
        Timer {
            id: itemToDesktopTimer
            interval: 600
            onTriggered: {
                GroupController.minimizeGroup()
            }
        }
        onPressed: {
            if (dragMousearea.Drag.active) {
                dragMousearea.drag.target = itemRoot
            }
        }
        onPressAndHold: {
            modelManager.setAllItemsState(LauncherItem.Editable)
            dragMousearea.Drag.active = true
            dragMousearea.drag.target = itemRoot
            startDrag(true)
        }
        onClicked: {
            switch (modelData.type) {
            case LauncherItem.AppIcon: {
                if (modelData.state === LauncherItem.Normal){
                    appManager.runApplication(modelData.desktopFile)
                }
                break;
            }

            case LauncherItem.Group: {
                if (modelData.state !== LauncherItem.Popup) {
                    GroupController.popupGroup(appIcon)
                }
                break;
            }
            default: break;
            }
            root.titleFocusChanged()
        }
        onPositionChanged:  {
            if (taskbar.replayAllowed) {
                appIcon.width = 64 * Style.tabletScaleFactor
                appIcon.height = 64 * Style.tabletScaleFactor
            }
            if (!taskbar.replayAllowed && itemRoot.Drag.active) {
                appIcon.width = type === LauncherItem.Group ? (88*Style.tabletScaleFactor*1.1) : (96*Style.tabletScaleFactor*1.1)
                appIcon.height = type === LauncherItem.Group ? (88*Style.tabletScaleFactor*1.1) : (96*Style.tabletScaleFactor*1.1)
            }
            Controller.tabletLauncherItemPositionChanged(item, listView,
                                                         moveDropArea, dragMousearea,
                                                         scrollingTimer)

            GroupPageController.taskbarItemPositionChanged(appIcon, changeContainerPageTimer,
                                                         dragMousearea, itemToDesktopTimer,
                                                         GroupController.groupContainer,
                                                         GroupController.groupContainerId,
                                                         GroupController.groupPopuped)

        }
        onReleased: {
            console.log("Launcher view release.")
            popUpTimer.stop()
            mouseAreaReleased = true
            isScrolling = false
            if (dragMousearea.Drag.active) {
                dragMousearea.Drag.active = false
                dragMousearea.drag.target = null
                if (taskbar.replayAllowed) {
                    if (modelData.type === LauncherItem.AppIcon) {
                        if (modelManager.replacePlaceholderItemTaskbar(visualIndex, pageIndex, -1, 0)) {
                            appIcon.visible = false
                            appName.visible = false
                        }
                    }
                    taskbar.replayAllowed = false
                } else if (GroupController.aboutToInsertGroup) {
                    GroupController.insertItemToGroup(visualIndex, pageIndex, modelData.id, appIcon, appName)
                } else {
                    modelManager.replacePlaceholderItem(visualIndex, pageIndex)
                }
                modelManager.updateCachedData()
                modelManager.updateCachedData(0)
            }
        }
    }
    Rectangle {
        id: item
        property bool moving: listView.horizontalVelocity
        width: modelData.columnSpan * Style.appIconGridWidth - Style.tabletScaleFactor * 40
        height: modelData.rowSpan * Style.appIconGridHeight - Style.tabletScaleFactor * 40
        color: "transparent"
        clip: false
        radius: 5
        anchors {
            horizontalCenter: parent.horizontalCenter;
            verticalCenter: parent.verticalCenter
        }

        AppIconContainer {
            id: appIcon
            anchors.centerIn: parent
            width: type === LauncherItem.Group ? 88 * Style.tabletScaleFactor : 96 * Style.tabletScaleFactor
            height: type === LauncherItem.Group ? 88 * Style.tabletScaleFactor : 96 * Style.tabletScaleFactor
            rootItem: pluginAnchorItem
            dropShadowOffset: 3
            deleteIconWidth: 40
            allowGroupItemToTaskbar: taskbar.replayAllowed
            widgetColumn: modelData.columnSpan
            widgetRow: modelData.rowSpan
            opacity: {
                if (modelData.type === LauncherItem.AppIcon) {
                    if (listView.moving || dragMousearea.Drag.active) {
                        return 1
                    }
                    if (dragMousearea.pressed && !dragMousearea.Drag.active) {
                        return 0.5
                    }
                }
                return 1
            }
            icon: {
                switch (modelData.type) {
                case LauncherItem.AppIcon: return "image://icons/" + modelData.icon
                case LauncherItem.AddIcon:
                    if (dragMousearea.pressed) {
                        return "qrc:/ui/images/list-add-click.svg";
                    } else {
                        return "qrc:/ui/images/list-add-default.svg";
                    }
                default: return ""
                }
            }
            type: modelData.type
            containerState: modelData.state
            groupModel: modelData.model
            groupName: modelData.name
            itemId: modelData.id
            onDeleteIconSig: {
                appIcon.visible = true
                console.log("begin ", rootWindow.desktopIsNotActived)
                UninstallJs.createUnInstallDialog(root, modelData.desktopFile,
                                                  modelData.name, modelData.icon,
                                                  rootWindow.desktopIsNotActived)

                taskbar.textPromptBox = model.modelData.name
                taskbar.iconPromptBox = modelData.icon
            }
            onGroupItemToDesktop: {
                if (!modelManager.itemExistsOnDesktop(itemId, pageIndex) && itemId !== -1) {
                    modelManager.addPlaceholderItem(modelManager.groupPageItemCount(-1, listView.currentIndex), listView.currentIndex)
                }
            }
        }
        GridViewDelegateItemText {
            id: appName
            color: "#FAFAFA"
            font: StylePrivate.StyleHelper.font
            verticalAlignment: Text.AlignVCenter
            anchors.top: appIcon.bottom
            anchors.horizontalCenter: appIcon.horizontalCenter
            anchors.topMargin: 6 * Style.tabletScaleFactor
            text: modelData.name
            width: appNameWidth
            visible: modelData.type !== LauncherItem.Placeholder &&
                     modelData.nameVisible &&
                     appIcon.containerState !== LauncherItem.Dragging &&
                     modelData.type !== LauncherItem.Widget
            layer.enabled: openGLEnabled
            layer.effect: DropShadow {
                verticalOffset: 1
                radius: 6
                samples: 12
            }
        }
    }
}
